<template>
  <div class="login">
    <div class="login_box">
      <div class="flex-box back">
        <a href="javascript:void(0);" @click="goBack">{{ $t('login.back') }}</a>
      </div>
      <div class="flex-box language">
        <el-select size="small" v-model="language" :placeholder="$t('text.pleaseSelect')" @change="setLanguage">
          <template #prefix>
            <img src="@/assets/en.png" class="lang-icon-s" alt="" v-if="language === 'en'" />
            <img src="@/assets/zh-cn.png" class="lang-icon-s" alt="" v-if="language === 'zh-cn'" />
          </template>
          <el-option v-for="item in languages" :key="item.value" :label="item.label" :value="item.value">
            <div class="lang-item">
              <img src="@/assets/en.png" class="lang-icon" alt="" v-if="item.value === 'en'" />
              <img src="@/assets/zh-cn.png" class="lang-icon" alt="" v-if="item.value === 'zh-cn'" />
              <span>{{ item.label }}</span>
            </div>
          </el-option>
        </el-select>
      </div>
      <div class="login_box_l">
        <template v-if="locale == 'en'">
          <LoginEn />
        </template>
        <template v-else-if="locale == 'zh-cn'">
          <LoginZhcn />
        </template>
      </div>
      <div class="login_box_inner">
        <div class="login_logo" style="margin-top: 54px">
          <h2>
            <span>{{ $t('button.login') }}</span>
          </h2>
        </div>
        <div class="login-main">
          <div class="login_main_inner" v-loading="formData.loading">
            <div class="login_item login_user">
              <input v-model.trim="formData.email" type="text" name="email" :placeholder="$t('input.account')" />
            </div>
            <div class="login_item login_pwd">
              <input v-model.trim="formData.password" type="password" name="password" :placeholder="$t('input.password')" />
            </div>
            <div class="login_item login_captcha clearfix">
              <div class="input_captcha">
                <input v-model.trim="formData.captcha" type="text" name="captcha" :placeholder="$t('input.verificationCode')" />
                <div class="get_captcha" @click="getCaptcha" v-loading="captchaData.loading" element-loading-custom-class="captcha_loading">
                  <a href="javascript:void(0);">
                    <img
                      v-if="captchaData.image"
                      :src="captchaData.image"
                      class="verifyimg reloadverify"
                      :title="$t('login.clickToSwitch')"
                    />
                  </a>
                </div>
              </div>
            </div>
            <div class="login_item agreement">
              <el-checkbox v-model="formData.checked" style="width: 420px">
                <span class="el-checkbox__label">
                  <span>{{ $t('login.agree') }}</span>
                  <a :href="$t('link.userServiceAgreement')" target="_blank">{{ $t('login.userServiceAgreement') }}</a>
                  <span>{{ $t('login.and') }}</span>
                  <a :href="$t('link.privacypolicy')" target="_blank">{{ $t('login.privacypolicy') }}</a>
                </span>
              </el-checkbox>
            </div>
            <div class="login_item login_bar">
              <a href="javascript:void(0);" @click="onSubmit">
                <span>{{ $t('button.login') }}</span>
              </a>
            </div>
            <div class="reg-tips">
              <p>
                <span>{{ $t('login.noAccount') }}</span>
                <a href="javascript:void(0);" @click="toRegister">{{ $t('login.goToRegister') }}</a>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
</div>
</template>

<script lang="ts" setup name="LoginPage">
  import { useRoute, useRouter } from 'vue-router';
  import { ref, reactive, onMounted } from 'vue';
  import { useUserStore } from '@/store/modules/user';
  import { captchaApi } from '@/api/index';
  import { useI18n } from 'vue-i18n';
  import { setLang } from '@/i18n';
  import LoginEn from '../components/login/en.vue';
  import LoginZhcn from '../components/login/zh-cn.vue';

  const { locale } = useI18n();

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const language = ref('en');
  const languages = ref([
    {
      value: 'en',
      label: 'English',
    },
    {
      value: 'zh-cn',
      label: '简体中文',
    },
  ]);

  const formData = reactive({
    email: '',
    password: '',
    captcha_key: '',
    captcha: '',
    checked: false,
    loading: false,
  });

  const captchaData = reactive({
    image: '',
    loading: false,
  });

  const setLanguage = (lang) => {
    setLang(lang);
  };

  const toCenter = () => {
    router.push({
      path: '/center',
      query: {
        t: new Date().getTime(),
      },
    });
  };

  const toRegister = () => {
    router.push({
      path: '/user/register',
      query: {
        t: new Date().getTime(),
      },
    });
  };

  const goBack = () => {
    if (locale.value == 'en') {
      window.location.href = 'https://ipxproxy.com/';
    } else if (locale.value == 'zh-cn') {
      window.location.href = 'https://zh.ipxproxy.com/';
    }
  };

  const getCaptcha = async () => {
    if (captchaData.loading) return false;
    captchaData.loading = true;
    captchaApi({})
      .then((res) => {
        captchaData.loading = false;
        formData.captcha_key = res.key || '';
        captchaData.image = res.image || '';
      })
      .catch((err) => {
        console.log('err', err);
        captchaData.loading = false;
        ElMessage.error(err.message);
      });
  };

  const onSubmit = async () => {
    if (!formData.email) {
      ElMessage.error('The email field is required');
      return false;
    }
    if (!formData.password) {
      ElMessage.error('The password field is required.');
      return false;
    }
    if (!formData.captcha) {
      ElMessage.error('The captcha field is required.');
      return false;
    }
    if (!formData.checked) {
      ElMessage.error('Please read the privacy policy first');
      return false;
    }
    if (formData.loading) return false;
    formData.loading = true;
    await userStore
      .login({
        ...formData,
      })
      .then((res) => {
        if (res && res.token) {
          toCenter(res.token);
        } else {
          getCaptcha();
        }
        formData.loading = false;
      });
  };

  onMounted(async () => {
    language.value = sessionStorage.getItem('lang') || 'en';
    await getCaptcha();
  });
</script>

<style scoped lang="scss">
  .login {
    padding: 20px;

    h2 {
      text-align: center;
    }

    .nut-form-item {
      margin-bottom: 20px;
      border-radius: 20px;
      background: #f2f3f5;

      input {
        background: transparent;
      }
    }
  }
</style>
